package com.monkeygroup.mygoplus.view.entrance.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.monkeygroup.mygoplus.MyGoApplication;
import com.monkeygroup.mygoplus.R;
import com.monkeygroup.mygoplus.ecchat.common.CCPAppManager;
import com.monkeygroup.mygoplus.ecchat.common.base.CCPFormInputView;
import com.monkeygroup.mygoplus.ecchat.common.dialog.ECProgressDialog;
import com.monkeygroup.mygoplus.ecchat.common.utils.ECPreferenceSettings;
import com.monkeygroup.mygoplus.ecchat.common.utils.ECPreferences;
import com.monkeygroup.mygoplus.ecchat.common.utils.FileAccessor;
import com.monkeygroup.mygoplus.ecchat.common.utils.PermissionUtils;
import com.monkeygroup.mygoplus.ecchat.common.utils.ToastUtil;
import com.monkeygroup.mygoplus.ecchat.core.ClientUser;
import com.monkeygroup.mygoplus.ecchat.core.ContactsCache;
import com.monkeygroup.mygoplus.ecchat.storage.ContactSqlManager;
import com.monkeygroup.mygoplus.ecchat.ui.ECSuperActivity;
import com.monkeygroup.mygoplus.ecchat.ui.SDKCoreHelper;
import com.monkeygroup.mygoplus.ecchat.ui.contact.ContactLogic;
import com.monkeygroup.mygoplus.ecchat.ui.contact.ECContacts;
import com.monkeygroup.mygoplus.view.entrance.fragment.LoginFragment;
import com.yuntongxun.ecsdk.ECDevice;
import com.yuntongxun.ecsdk.ECInitParams;
import com.yuntongxun.ecsdk.SdkErrorCode;

import java.io.InvalidClassException;
import java.util.ArrayList;

/**
 * Created by Administrator on 2017/5/15.
 */
public class EntranceActivity extends ECSuperActivity {

    private EditText appkeyEt;
    private EditText tokenEt;
    private EditText mobileEt;
    private EditText mVoipEt;
    private Button signBtn;
    private LinearLayout llImg;
    private CCPFormInputView mFormInputView;
    private CCPFormInputView mFormInputViewPassword;
    private ECProgressDialog mPostingdialog;
    ECInitParams.LoginAuthType mLoginAuthType = ECInitParams.LoginAuthType.NORMAL_AUTH;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

//        initResourceRefs();
        registerReceiver(new String[]{SDKCoreHelper.ACTION_SDK_CONNECT});
        PermissionUtils.requestMultiPermissions(this, mPermissionGrant);
        //不显示标题TOPBar
        hideTitleView();
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        if (MyGoApplication.statusHight != 0) {
            findViewById(R.id.layout_title).setPadding(0, MyGoApplication.statusHight, 0, 0);
        } else {
            findViewById(R.id.layout_title).setPadding(0, 40, 0, 0);
        }

        doEvent();
    }

    public static void gotoActivity(Activity activity) {
        Intent intent = new Intent(activity,
                EntranceActivity.class);

//        intent.putExtra("strPainpointid", strPainpointid);
//        intent.putExtra("type", type);
        activity.startActivity(intent);
    }


    public void doEvent() {

        getFragmentManager().beginTransaction().replace(R.id.fragment_container, new LoginFragment()).commit();
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionUtils.requestPermissionsResult(this, requestCode, permissions, grantResults, mPermissionGrant);
    }


    private PermissionUtils.PermissionGrant mPermissionGrant = new PermissionUtils.PermissionGrant() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode) {
                case PermissionUtils.CODE_MULTI_PERMISSION:
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    protected void onResume() {

        super.onResume();
//        initConfig();
    }

//    private void initConfig() {
//
//        String appkey = FileAccessor.getAppKey();
//        String token = FileAccessor.getAppToken();
//        appkeyEt.setText(appkey);
//        tokenEt.setText(token);
//
//        if (TextUtils.isEmpty(appkey) || TextUtils.isEmpty(token)) {
//            signBtn.setEnabled(false);
//            ToastUtil.showMessage(R.string.app_server_config_error_tips);
//        }
//    }

//    private void initResourceRefs() {
//        ipEt = (EditText) findViewById(R.id.ip);
//        portEt = (EditText) findViewById(R.id.port);
//        appkeyEt = (EditText) findViewById(R.id.appkey);
//        tokenEt = (EditText) findViewById(R.id.token);
//        mFormInputView = (CCPFormInputView) findViewById(R.id.mobile);
//        mobileEt = mFormInputView.getFormInputEditView();
////		mobileEt.setInputType(InputType.TYPE_CLASS_PHONE);
//        mFormInputViewPassword = (CCPFormInputView) findViewById(R.id.VoIP_mode);
//        mVoipEt = mFormInputViewPassword.getFormInputEditView();
//        // mVoipEt.setInputType(InputType.TYPE_CLASS_PHONE);
//        mobileEt.requestFocus();
//        // mobileEt.setText(ECSDKUtils.getLine1Number(this));
//        signBtn = (Button) findViewById(R.id.sign_in_button);
//
//    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onActivityInit() {
        // super.onActivityInit();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_entrance;
    }

    private boolean flag = true;

    public void showDialog() {
        mPostingdialog = new ECProgressDialog(this, R.string.login_posting);
        mPostingdialog.show();
    }

    /**
     * 关闭对话框
     */
    private void dismissPostingDialog() {
        if (mPostingdialog == null || !mPostingdialog.isShowing()) {
            return;
        }
        mPostingdialog.dismiss();
        mPostingdialog = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x2a) {
            doLauncherAction();
        }
    }

    public void initECLoginConfig(String mobile) {
        String appkey = FileAccessor.getAppKey();
        String token = FileAccessor.getAppToken();

        ClientUser clientUser = new ClientUser(mobile);
        clientUser.setAppKey(appkey);
        clientUser.setAppToken(token);
        clientUser.setLoginAuthType(ECInitParams.LoginAuthType.NORMAL_AUTH);
        clientUser.setPassword("");
        CCPAppManager.setClientUser(clientUser);

        showDialog();
        SDKCoreHelper.init(this, ECInitParams.LoginMode.FORCE_LOGIN);
    }

    private void doLauncherAction() {
        try {
            MyGoApplication.loginFlag = true;

//            Intent intent = new Intent(this, LauncherActivity.class);
//            intent.putExtra("launcher_from", 1);
//            // 注册成功跳转
//            startActivity(intent);

            finish();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void saveAccount() throws InvalidClassException {
//        String appKey = FileAccessor.getAppKey();
//        String token = FileAccessor.getAppToken();
//        String mobile = CCPAppManager.getClientUser().getUserId();
//        String voippass = "";
        ClientUser user = CCPAppManager.getClientUser();
//        if (user == null) {
//            user = new ClientUser(mobile);
//        } else {
//            user.setUserId(mobile);
//        }
//        user.setAppToken(token);
//        user.setAppKey(appKey);
//        user.setPassword(voippass);
//        user.setLoginAuthType(mLoginAuthType);
//        CCPAppManager.setClientUser(user);
        ECPreferences.savePreference(ECPreferenceSettings.SETTINGS_REGIST_AUTO, user.toString(), true);
        // ContactSqlManager.insertContacts(contacts);
        ArrayList<ECContacts> objects = ContactLogic.initContacts();
        objects = ContactLogic.converContacts(objects);
        ContactSqlManager.insertContacts(objects);
    }

    @Override
    protected void handleReceiver(Context context, Intent intent) {
        // super.handleReceiver(context, intent);
        int error = intent.getIntExtra("error", -1);
        if (SDKCoreHelper.ACTION_SDK_CONNECT.equals(intent.getAction())) {
            // 初始注册结果，成功或者失败
            if (SDKCoreHelper.getConnectState() == ECDevice.ECConnectState.CONNECT_SUCCESS
                    && error == SdkErrorCode.REQUEST_SUCCESS) {
                dismissPostingDialog();
                try {
                    saveAccount();
                } catch (InvalidClassException e) {
                    e.printStackTrace();
                }
                ContactsCache.getInstance().load();
                doLauncherAction();
                return;
            }
            if (intent.hasExtra("error")) {
                if (SdkErrorCode.CONNECTTING == error) {
                    return;
                }
                if (error == -1) {
                    ToastUtil.showMessage("请检查登陆参数是否正确[" + error + "]");
                } else {
                    dismissPostingDialog();
                }
                ToastUtil.showMessage("登录失败，请稍后重试[" + error + "]");
            }
            dismissPostingDialog();
        }


    }

    @Override
    protected boolean isEnableSwipe() {
        return false;
    }

    @Override
    public boolean isEnableRightSlideGesture() {
        return false;
    }

    @Override
    public void abstracrRegist() {
    }
}